import * as types from '../mutation-types'
import DEVICE_TYPES from 'config/device-types'
import _ from 'lodash'
import api from 'api'
import PRODUCTIDS from 'config/product-ids'
import PMDATA from 'static/data/devices/pm25.json'
import appId from 'config/pm25'

// let methods = {
//   /**
//    * 获取历史数据
//    * @param  {Number} number 查询日期
//    * @return {Object}
//    */
//   params (number) {
//     let year = new Date().getFullYear()
//     let month = new Date().getMonth()
//     let date = new Date().getDate()
//     console.log(new Date(new Date(`${year}/${month}/${date}`) - number * 1000 * 60 * 60 * 24))
//     console.log(new Date(`${year}/${month}/${date}`))
//     let params = {
//       'offset': 0,
//       'limit': 2500,
//       'date': {
//         'begin': new Date(new Date(`${year}/${month}/${date}`) - number * 1000 * 60 * 60 * 24),
//         'end': new Date(`${year}/${month}/${date}`)
//       }
//     }
//     return params
//   }
// }
// initial state
const state = {
  devices: [],
  temperatureHumidityHistory: [],
  tvocPM25FormaldehydeHistory: [],
  tvocPM25FormaldehydeSevenHistory: [],
  tvocPM25FormaldehydeThirtyHistory: [],
  tvocPM25FormaldehydeNowday: [],
  publicPM25: []
}

// actions
const actions = {
  updatePM25 ({ commit }, deviceStatus) {
    let pmId = []
    PMDATA.forEach(element => {
      let pm
      pm = _.find(element.devices, (item) => {
        return item.type === DEVICE_TYPES.PM25
      })
      pm['title'] = element.title
      pmId.push(pm)
    })
    pmId.forEach(item => {
      api.device.getVDevice(PRODUCTIDS[DEVICE_TYPES.PM25], item.id).then(function (doc) {
        if (typeof doc.data[0] === 'number') {
          let obj = {
            id: item.id,
            type: DEVICE_TYPES.PM25,
            data: {
              '0': doc.data[0],
              '1': doc.data[1],
              '2': doc.data[2],
              '3': doc.data[3],
              '4': doc.data[4],
              '5': doc.data[5]
            },
            room: item.title // 所属位置
          }
          commit(types.UPDATE_PM25, obj)
        }
      })
    })
  },
  // 获取空气设备温度湿度历史最近24小时数据 160fa6b1d60f03e9160fa6b1d60f1601 1049157557
  updateHistoryTemperatureHumidity ({ commit }) {
    // let ioProductId = '160fa6b1d60f03e9160fa6b1d60f1601'
    // let deviceId = '1049157557'
    // let params = {
    //   'offset': 0,
    //   'limit': 2500,
    //   'date': {
    //     'begin': new Date() - 1000 * 60 * 60 * 24,
    //     'end': +new Date()
    //   }
    // }
    // api.snapshot.getSnapshot(ioProductId, deviceId, params).then((res) => {
      // commit(types.UPDATE_TEMPERATURE_HUMIDITY_HISTORY, res.data.list)
    // }).catch((res) => {
    //   console.log(res)
    // })
  },
  // 获取空气设备tvoc,PM25,甲醛昨日历史数据 获取空气设备tvoc,甲醛七日,PM25三十天历史数据
  updateHistoryTvocPM25Formaldehyde ({ commit }, day) {
    // let ioProductId = '160fa6b1d60f03e9160fa6b1d60f1601'
    // let deviceId = '1049157557'
    // let params = methods.params(day)
    // console.log(params)
    // if (day === 7) {
    //   api.snapshot.getSnapshot(ioProductId, deviceId, params).then((res) => {
    //     commit(types.UPDATE_TVOC_PM25_FORMALDEHYDE_SEVEN_HISTORY, res.data.list)
    //   }).catch((res) => {
    //     console.log(res)
    //   })
    // } else if (day === 1) {
    //   api.snapshot.getSnapshot(ioProductId, deviceId, params).then((res) => {
    //     commit(types.UPDATE_TVOC_PM25_FORMALDEHYDE_HISTORY, res.data.list)
    //   }).catch((res) => {
    //     console.log(res)
    //   })
    // } else {
    //   api.snapshot.getSnapshot(ioProductId, deviceId, params).then((res) => {
    //     commit(types.UPDATE_TVOC_PM25_FORMALDEHYDE_THIRTY_HISTORY, res.data.list)
    //   }).catch((res) => {
    //     console.log(res)
    //   })
    // }
  },
  // 获取空气设备tvocPM25甲醛今日数据
  updateNowdayTvocPM25Formaldehyde ({ commit }) {
    // let ioProductId = '160fa6b1d60f03e9160fa6b1d60f1601'
    // let deviceId = '1049157557'
    // let day = new Date().getFullYear()
    // let month = new Date().getMonth()
    // let date = new Date().getDate()
    // console.log(new Date(new Date(`${day}/${month}/${date}`) - 1000 * 60 * 60 * 24))
    // console.log(new Date(`${day}/${month}/${date}`))
    // let params = {
    //   'offset': 0,
    //   'limit': 2500,
    //   'date': {
    //     'begin': new Date(`${day}/${month}/${date}`),
    //     'end': new Date()
    //   }
    // }
    // api.snapshot.getSnapshot(ioProductId, deviceId, params).then((res) => {
    //   commit(types.UPDATE_TVOC_PM25_FORMALDEHYDE_NOWDAY, res.data.list)
    // }).catch((res) => {
    //   console.log(res)
    // })
  },
  updatePublicPM25 ({ commit }) {
    // appToken是否过期标志位
    var id = appId.appId
    // var id = '2e0fa6b179fec604'
    var params = {
      'app_id': id
    }
    let year = new Date().getFullYear()
    let month = new Date().getMonth() + 1
    let date = new Date().getDate()
    // let historyYear = new Date(new Date() - 60 * 1000 * 60 * 24 * 30).getFullYear()
    // let historyMonth = new Date(new Date() - 60 * 1000 * 60 * 24 * 30).getMonth() + 1
    // let historyDate = new Date(new Date() - 60 * 1000 * 60 * 24 * 30).getDate()
    let timeArr = []
    for (let i = 0, len = 30; i < len; i++) {
      let obj = {
        nowday: new Date(new Date(`${year}/${month}/${date} 23:59:59`) - 60 * 1000 * 60 * 24 * i),
        yesterday: new Date(new Date(`${year}/${month}/${date} 23:59:59`) - 60 * 1000 * 60 * 24 * (i + 1)),
        data: 0,
        number: 0
      }
      timeArr.push(obj)
    }
    // let pm25Params = {
    //   'cid': 'qiye',
    //   'uid': 2,
    //   'pid': 'chanpinid',
    //   'did': 'shebeiid',
    //   'scene_type': 1,
    //   'photo_url': '照片链接',
    //   'photo_time': new Date() - 60 * 1000 * 60 * 24 * 10,
    //   'out_longitude': 123.2321,
    //   'out_latitude': 321.12321,
    //   'out_province': '广西',
    //   'out_city': '广西',
    //   'out_district': '广西',
    //   'out_place': '广西',
    //   'out_pm2o5': 2,
    //   'out_aqi': 2,
    //   'out_temp': 2,
    //   'out_humidity': 2,
    //   'pm1o0_unit': 2,
    //   'pm2o5_unit': 2,
    //   'pm10_unit': 2,
    //   'pm1o0': 2,
    //   'pm2o5': 4,
    //   'pm10': 4,
    //   'um0o3': 2,
    //   'um0o5': 2,
    //   'um1o0': 2,
    //   'um2o5': 2,
    //   'um5o0': 2,
    //   'um10': 2,
    //   'formaldehyde': 4.2,
    //   'pollution_level': 3,
    //   'belong': 0
    // }
    let pm25Params = {
      'offset': '0',
      'limit': '100',
      // 'filter': ['字段A', '字段B'],
      'query': {
        // 'label': {'$in': ['产品建议']}
        // 'out_province': {'$in': ['广东']},
        // 'pollution_level': {'$in': '3'}
        // 'filed3': {'$lt': '字段值'}
      }
      // 'order': {
      //   'field.filed1': 1,
      //   'filed2': -1
      // }
    }
    // 保存30天内
    api.plugin.getAppToKen(params, window.localStorage.getItem('accessToken')).then((res) => {
      window.localStorage.setItem('appToken', res.data.access_token)
      // for (let i = 0; i < 1000; i++) {
      api.pm25.pm25(id, pm25Params).then((res) => {
        res.data.list.forEach((item, index) => {
          timeArr.forEach((element, i) => {
            if (element.nowday > new Date(item.update_time) && new Date(item.update_time) > element.yesterday) {
              element.data += parseInt(item.pm25)
              element.number++
            }
          })
        })
        commit(types.UPDATE_PM25_PUBLIC, timeArr)
      })
      // }
    }).catch((err) => {
      console.log(err)
    })
  }
}

// getters
const getters = {
  // pm25实时数据
  pm25 () {
    return _.find(state.devices, (item) => {
      return item.type === DEVICE_TYPES.PM25
    })
  },
  // 昨日PM2.5平均值
  pm25HistoryPM25 () {
    // if (state.tvocPM25FormaldehydeHistory.length === 0) {
    //   return
    // }
    // let pm25 = state.tvocPM25FormaldehydeHistory.map(item => item['0'] || 0)
    // let total = 0
    // pm25.forEach((item) => {
    //   total += item
    // })
    // return total / 24
    return 26.9
  },
  // 今日PM2.5平均值，假如没有值的时候取得昨日最后一个值
  pm25NowdayPM25 () {
    // if (state.tvocPM25FormaldehydeNowday.length === 0) {
    //   if (!(state.tvocPM25FormaldehydeHistory.map(item => item['0'] || 0).length === 0)) {
    //     return state.tvocPM25FormaldehydeHistory.map(item => item['0'] || 0)[23]
    //   }
    //   return 0
    // }
    // let pm25 = state.tvocPM25FormaldehydeNowday.map(item => item['0'] || 0)
    // let total = 0
    // pm25.forEach((item) => {
    //   total += item
    // })
    // return total / 24
    return 28.2
  },
  // 昨日tvoc平均值
  pm25HistoryTvoc () {
    // if (state.tvocPM25FormaldehydeHistory.length === 0) {
    //   return
    // }
    // let total = 0
    // let pm25 = state.tvocPM25FormaldehydeHistory.map(item => item['1'] || 0)
    // pm25.forEach((item) => {
    //   total += item
    // })
    // return total / 24
    return 0.26
  },
  // 今日tvoc平均值，假如没有值的时候取得昨日最后一个值
  pm25NowdayTvoc () {
    // if (state.tvocPM25FormaldehydeNowday.length === 0) {
    //   if (!(state.tvocPM25FormaldehydeHistory.map(item => item['1'] || 0).length === 0)) {
    //     return state.tvocPM25FormaldehydeHistory.map(item => item['1'] || 0)[23]
    //   }
    //   return 0
    // }
    // let pm25 = state.tvocPM25FormaldehydeNowday.map(item => item['1'] || 0)
    // let total = 0
    // pm25.forEach((item) => {
    //   total += item
    // })
    // return total / 24
    return 0.23
  },
  // 昨日甲醛平均值
  pm25Historyformaldehyde () {
    // if (state.tvocPM25FormaldehydeHistory.length === 0) {
    //   return
    // }
    // let total = 0
    // let pm25 = state.tvocPM25FormaldehydeHistory.map(item => item['2'] || 0)
    // pm25.forEach((item) => {
    //   total += item
    // })
    // return total / 24
    return 11
  },
  // 今日甲醛平均值，假如没有值的时候取得昨日最后一个值
  pm25NowdayFormaldehyde () {
    // if (state.tvocPM25FormaldehydeNowday.length === 0) {
    //   if (!(state.tvocPM25FormaldehydeHistory.map(item => item['2'] || 0).length === 0)) {
    //     return state.tvocPM25FormaldehydeHistory.map(item => item['2'] || 0)[23]
    //   }
    //   return 0
    // }
    // let pm25 = state.tvocPM25FormaldehydeNowday.map(item => item['2'] || 0)
    // let total = 0
    // pm25.forEach((item) => {
    //   total += item
    // })
    // return total / 24
    return 10
  },
  // 最近24小时温度数据
  pm25HistoryTemperature () {
    // if (state.temperatureHumidityHistory.length === 0) {
    //   return
    // }
    // 给的假数据
    return [24.9, 27.2, 28.3, 24.9, 27.2, 19.2, 16.8, 24.3, 28.3, 24.9, 19.2, 16.8, 24.3, 28.3, 28, 27.2, 19.2, 16.8, 24.3, 25, 19.2, 16.8, 24.3, 28.3]
    // return state.temperatureHumidityHistory.map(item => item['3'] || 0)
  },
  // 最近24小时湿度数据
  pm25HistoryHumidity () {
    // if (state.temperatureHumidityHistory.length === 0) {
    //   return
    // }
    // return state.temperatureHumidityHistory.map(item => item['4'] || 0)
    return [55, 60, 59, 66, 59, 64, 69, 62, 63, 66, 59, 65, 66, 62, 54, 66, 59, 59, 69, 62, 58, 64, 69, 62]
  },
  // tvoc最近7天数据 每天一个值（平均值）
  tovcSevenHistory () {
    // 配合假数据注释掉了
    // if (state.tvocPM25FormaldehydeSevenHistory.length === 0) {
    //   return
    // }
    let arrytvoc = state.tvocPM25FormaldehydeSevenHistory.map(item => item['1'] || 0)
    let arr = []
    let total = 0
    arrytvoc.forEach((item, index) => {
      if ((index + 1) % 24 === 0) {
        arr.push(parseInt(total / 24))
        total = 0
      } else {
        total += item
      }
    })
    // return arr
    // 假数据
    return [8, 11, 8, 6, 7, 12, 8]
  },
  // 甲醛最近7天数据 每天一个值（平均值）
  formaldehydeSevenHistory () {
    // 配合假数据注释掉了
    // if (state.tvocPM25FormaldehydeSevenHistory.length === 0) {
    //   return
    // }
    let arrytvoc = state.tvocPM25FormaldehydeSevenHistory.map(item => item['2'] || 0)
    let arr = []
    let total = 0
    arrytvoc.forEach((item, index) => {
      if ((index + 1) % 24 === 0) {
        arr.push(parseInt(total / 24))
        total = 0
      } else {
        total += item
      }
    })
    // return arr
    // 假数据
    return [10, 8, 10, 8, 9, 10, 7]
  },
  // pm最近30天数据 每天一个值（平均值）
  pm25ThirtyHistory () {
    // 配合假数据注释掉了
    // if (state.tvocPM25FormaldehydeThirtyHistory.length === 0) {
    //   return
    // }
    let arrytvoc = state.tvocPM25FormaldehydeThirtyHistory.map(item => item['0'] || 0)
    let arr = []
    let total = 0
    arrytvoc.forEach((item, index) => {
      if ((index + 1) % 24 === 0) {
        arr.push(parseInt(total / 24))
        total = 0
      } else {
        total += item
      }
    })
    // return arr
    // 假数据
    return [24.9, 23.6, 16.3, 24.6, 26.8, 24.6, 26.8, 24.9, 23.6, 16.3, 24.6, 26.8, 24.9, 23.6, 16.3, 24.6, 26.8, 24.9, 23.6, 24.2, 24.6, 26.8, 24.9, 23.6, 16.3, 24.6, 26.8, 24.9, 23.6, 16.3]
  },
  publicPm25History () {
    let res = []
    if (!state.publicPM25[0]) {
      return
    }
    state.publicPM25[0].forEach((item, index) => {
      if (item.number !== 0) {
        res.push((item.data / item.number).toFixed(1))
      } else {
        res.push((state.publicPM25[state.publicPM25.length - 2].data / state.publicPM25[state.publicPM25.length - 2].number).toFixed(1))
      }
    })
    window.localStorage.setItem('pm', res)
    return res
  }
}

// mutations
const mutations = {
  [types.UPDATE_PM25] (state, obj) {
    let finded = _.find(state.devices, (item) => {
      return item.id === obj.id
    })
    if (finded) {
      state.devices = _.filter(state.devices, (item) => {
        return item.id !== obj.id
      })
    }
    state.devices.push(obj)
  },
  [types.UPDATE_TEMPERATURE_HUMIDITY_HISTORY] (state, obj) {
    // let finded = _.find(state.temperatureHumidityHistory, (item) => {
    //   return item.id === obj.id
    // })
    // if (finded) {
    //   state.temperatureHumidityHistory = _.filter(state.temperatureHumidityHistory, (item) => {
    //     return item.id !== obj.id
    //   })
    // }
    state.temperatureHumidityHistory.push(obj)
  },
  [types.UPDATE_TVOC_PM25_FORMALDEHYDE_HISTORY] (state, obj) {
    // let finded = _.find(state.tvocPM25FormaldehydeHistory, (item) => {
    //   return item.id === obj.id
    // })
    // if (finded) {
    //   state.tvocPM25FormaldehydeHistory = _.filter(state.tvocPM25FormaldehydeHistory, (item) => {
    //     return item.id !== obj.id
    //   })
    // }
    state.tvocPM25FormaldehydeHistory.push(obj)
  },
  [types.UPDATE_TVOC_PM25_FORMALDEHYDE_NOWDAY] (state, obj) {
    // let finded = _.find(state.tvocPM25FormaldehydeNowday, (item) => {
    //   return item.id === obj.id
    // })
    // if (finded) {
    //   state.tvocPM25FormaldehydeNowday = _.filter(state.tvocPM25FormaldehydeNowday, (item) => {
    //     return item.id !== obj.id
    //   })
    // }
    state.tvocPM25FormaldehydeNowday.push(obj)
  },
  [types.UPDATE_TVOC_PM25_FORMALDEHYDE_SEVEN_HISTORY] (state, obj) {
    // let finded = _.find(state.tvocPM25FormaldehydeSevenHistory, (item) => {
    //   return item.id === obj.id
    // })
    // if (finded) {
    //   state.tvocPM25FormaldehydeSevenHistory = _.filter(state.tvocPM25FormaldehydeSevenHistory, (item) => {
    //     return item.id !== obj.id
    //   })
    // }
    state.tvocPM25FormaldehydeSevenHistory.push(obj)
  },
  [types.UPDATE_TVOC_PM25_FORMALDEHYDE_THIRTY_HISTORY] (state, obj) {
    // let finded = _.find(state.tvocPM25FormaldehydeSevenHistory, (item) => {
    //   return item.id === obj.id
    // })
    // if (finded) {
    //   state.tvocPM25FormaldehydeSevenHistory = _.filter(state.tvocPM25FormaldehydeSevenHistory, (item) => {
    //     return item.id !== obj.id
    //   })
    // }
    state.tvocPM25FormaldehydeThirtyHistory.push(obj)
  },
  [types.UPDATE_PM25_PUBLIC] (state, obj) {
    // let finded = _.find(state.tvocPM25FormaldehydeSevenHistory, (item) => {
    //   return item.id === obj.id
    // })
    // if (finded) {
    //   state.tvocPM25FormaldehydeSevenHistory = _.filter(state.tvocPM25FormaldehydeSevenHistory, (item) => {
    //     return item.id !== obj.id
    //   })
    // }
    state.publicPM25.push(obj)
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
